package logic

import (
	"context"
	"develop/model/cache"
	"develop/model/mysql"
	"develop/usersrpc/internal/svc"
	"develop/usersrpc/usersrpc"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePwdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdatePwdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePwdLogic {
	return &UpdatePwdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdatePwdLogic) UpdatePwd(in *usersrpc.UpdatePwdRequest) (*usersrpc.UpdatePwdResponse, error) {
	// todo: add your logic here and delete this line
	var findUserId mysql.User_info
	err := findUserId.FindId(mysql.DB, in.UserId)
	if err != nil {
		return nil, err
	}
	if findUserId.ID == 0 {
		return nil, errors.New("用户不存在")
	}
	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.PhoneNum).Result()
	if result != in.SendSmsCode {
		return nil, errors.New("短信验证码不正确")
	}
	if in.Pwd != in.NewPwd {
		return nil, errors.New("两次密码不一致,请重新输入")
	}
	if in.Pwd == findUserId.Pwd {
		return nil, errors.New("新密码与原密码一致,请重新输入")
	}
	findUserId.Pwd = in.Pwd
	err = findUserId.UpdatePassword(mysql.DB)
	if err != nil {
		return nil, err
	}
	return &usersrpc.UpdatePwdResponse{
		UserId: int64(findUserId.ID),
	}, nil
}
